<?php
declare (strict_types=1);

namespace app\command;

use app\job\Task;
use app\model\Config;
use app\model\User;
use app\model\UserLayer;
use app\model\VipOrders;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Queue;

class UpdateLevel extends Command
{
	protected function configure()
	{
		// 指令配置
		$this->setName('updatelevel')
			->setDescription('the updatelevel command');
	}
	
	protected function execute(Input $input, Output $output)
	{
		// 指令输出
		
		$hehuo = User::where(['level' => 3])->select();
		$gaoji = User::where(['level' => 4])->select();
		$hehuo_team_amount = Config::getFieldByName('hehuo_team_amount', 'value');
		$hehuo_advance_num = Config::getFieldByName('hehuo_advance_num', 'value');
		$gaoji_team_gaoji = Config::getFieldByName('gaoji_team_gaoji', 'value');
		$gaoji_team_yeji = Config::getFieldByName('gaoji_team_yeji', 'value');
		$gaoji_advance_num = Config::getFieldByName('gaoji_advance_num', 'value');
		$vip_expire = Config::getFieldByName('vip_expire', 'value');
		foreach ($hehuo as $item) {
			$up = 0;
			$user_ids = UserLayer::where(['pid' => $item->id, 'level' => 1])->limit(2)->column('user_id');
			$layers = User::whereIn('id', $user_ids)->where(['level' => 3])->count();
			if ($layers >= 1) {
				$up += 1;
			}
			$team_uids = UserLayer::whereIn('pid', $user_ids)->column('user_id');
			$team_uids = array_merge($team_uids, $user_ids);
			$yeji = VipOrders::whereIn('user_id', $team_uids)->where(['status' => 2])->sum('pay_amount');
			
			if ($yeji >= $hehuo_team_amount) {
				$up += 1;
			}
			$zhijie = UserLayer::where(['pid' => $item->id, 'level' => 1])->count();
			if ($zhijie >= $hehuo_advance_num) {
				$up += 1;
			}
			
			if ($up >= 3) {
				$time = time();
				$item->level = 4;
				$item->vip_expiretime = strtotime("$vip_expire", $time);
				$item->save();
			}
		}
		foreach ($gaoji as $value) {
			$up = 0;
			$gaoji_team = UserLayer::where(['pid' => $value->id])->column('user_id');
			$gaoji_num = User::whereIn('id', $gaoji_team)->where(['level' => 4])->count();
			if ($gaoji_num >= $gaoji_team_gaoji) {
				$up += 1;
			}
			$gaoji_team[] = $value->id;
			$yeji = VipOrders::whereIn('user_id', $gaoji_team)->where(['status' => 2])->sum('pay_amount');
			if ($yeji >= $gaoji_team_yeji) {
				$up += 1;
			}
			$zhijie = UserLayer::where(['pid' => $value->id, 'level' => 1])->count();
			if ($zhijie >= $gaoji_advance_num) {
				$up += 1;
			}
			if ($up >= 3) {
				$time = time();
				$value->level = 5;
				$value->vip_expiretime = strtotime("$vip_expire", $time);
				$value->save();
			}
		}
		
		$output->writeln('updatelevel');
	}
}
